package org.scohen.juploadr.uploadapi.flickrrest.geo;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.eclipse.swt.SWT;
import org.scohen.juploadr.app.UploadImage;
import org.scohen.juploadr.ui.MessageUtils;
import org.scohen.juploadr.ui.Task;
import org.scohen.juploadr.uploadapi.CommunicationException;
import org.scohen.juploadr.uploadapi.ProtocolException;
import org.scohen.juploadr.util.JUploadrBrowserLauncher;

public class SetLocationTask extends Task {
    private List<UploadImage> toSetLocations = new ArrayList<UploadImage>();
    private String photoName;

    public SetLocationTask(Collection<? extends UploadImage> images) {
        for (UploadImage img : images) {
            if (img.getLocation() != null) {
                toSetLocations.add(img);
            }
        }
        this.min = 0;
        this.max = toSetLocations.size();
        if (!toSetLocations.isEmpty()) {
            photoName = toSetLocations.get(0).getTitle();
        }
    }

    @Override
    public void execute() {
        if (!toSetLocations.isEmpty()) {
            try {
                setLocations();

            } catch (UserNotConfiguredException unc) {
                JUploadrBrowserLauncher.openURL("http://www.flickr.com/account/geo/privacy/");
                if (MessageUtils
                        .showMessage(
                                "In order to set locations, you must first set privacy. Click OK to open the privacy setting window",
                                "set privacy", SWT.ICON_INFORMATION)) {
                    execute();
                }

            } catch (ProtocolException e) {
                System.out.println(e);
            } catch (CommunicationException e) {
                System.out.println(e);
            }
        }
    }

    /**
     * @throws ProtocolException
     * @throws CommunicationException
     */
    private void setLocations() throws ProtocolException, CommunicationException {
        int cur = 1;
        for (UploadImage img : toSetLocations) {
            photoName = img.getTitle();
            updateProgress(cur++);
            SetLocation l = new SetLocation(img);
            l.execute();
        }
    }

    public boolean hasPhotosToGeoTag() {
        return !toSetLocations.isEmpty();
    }

    @Override
    public String getMessage() {
        return "Adding location to " + photoName;
    }

    @Override
    public String getTitle() {
        return "Adding locations to " + toSetLocations.size() + " photos";
    }

}
